package com.shiwaixiangcun.customer.ui.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.shiwaixiangcun.customer.GlobalApi;
import com.shiwaixiangcun.customer.R;
import com.shiwaixiangcun.customer.base.BaseActivity;
import com.shiwaixiangcun.customer.entity.VersionBean;
import com.shiwaixiangcun.customer.event.EventUtil;
import com.shiwaixiangcun.customer.event.SimpleEvent;
import com.shiwaixiangcun.customer.helper.UpdateHelper;
import com.shiwaixiangcun.customer.ui.fragment.FragmentMain;
import com.shiwaixiangcun.customer.ui.fragment.FragmentMall;
import com.shiwaixiangcun.customer.ui.fragment.FragmentMine;
import com.shiwaixiangcun.customer.update.UpdateAppManager;
import com.shiwaixiangcun.customer.utils.OkGoUpdateHttpUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author Administrator
 * @date 2017/9/21
 * HOME   页面
 */

public class MainActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.main_content)
    FrameLayout mMainContent;
    @BindView(R.id.llayout_home)
    LinearLayout mLlayoutHome;
    @BindView(R.id.llayout_mall)
    LinearLayout mLlayoutMall;
    @BindView(R.id.llayout_me)
    LinearLayout mLlayoutMe;
    @BindView(R.id.layout_bottom_bar)
    LinearLayout mLayoutBottomBar;
    private FragmentMain mFragmentHome;
    private FragmentMall mFragmentMall;
    private FragmentMine mFragmentMine;
    private Fragment mCurrentFragment;
    private long exitTime;
    private FragmentManager mFragmentManager;
    private String updateUrl;
    private int versionCode;
    private int updateCode = -1;
    protected ImmersionBar mImmersionBar;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        EventUtil.getInstance().register(this);
        ButterKnife.bind(this);
        versionCode = UpdateHelper.getInstance().getVersionCode(this);
        updateCode = UpdateHelper.getInstance().getVersionCode(this);
        updateUrl = GlobalApi.INSTANCE.getAppUpdate();
        //初始化沉浸式
        if (isImmersionBarEnabled()) {
            initImmersionBar();
        }
        checkAndUpdate();
        initView();

    }

    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.fitsSystemWindows(true)
                .statusBarColor(R.color.colorPrimary)
                .init();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(SimpleEvent simpleEvent) {
        if (simpleEvent.mEventType != SimpleEvent.UPDATE_VERSION) {
            return;
        }
        switch (simpleEvent.mEventValue) {
            case 1:
                VersionBean versionBean = (VersionBean) simpleEvent.getData();
//                showUpdateDialog(versionBean.getLatestVersion(), versionBean.getDownloadUrl(), "");
                break;
            case 2:
                initView();
                break;
            case 3:
                initView();
                break;
            default:
                initView();
                break;
        }
    }

    /**
     * 初始化视图
     */
    private void initView() {
        mLlayoutHome.setOnClickListener(this);
        mLlayoutMall.setOnClickListener(this);
        mLlayoutMe.setOnClickListener(this);
        mFragmentManager = getSupportFragmentManager();
        mFragmentHome = new FragmentMain();
        mFragmentMall = new FragmentMall();
        mFragmentMine = new FragmentMine();
        mCurrentFragment = mFragmentHome;
        mFragmentManager.beginTransaction().add(R.id.main_content, mFragmentHome).commitNow();
        setSelect(mLlayoutHome, true);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llayout_home:
                setSelect(mLlayoutHome, true);
                setSelect(mLlayoutMall, false);
                setSelect(mLlayoutMe, false);
                switchFragment(mFragmentHome).commit();
                break;
            case R.id.llayout_mall:
                setSelect(mLlayoutHome, false);
                setSelect(mLlayoutMall, true);
                setSelect(mLlayoutMe, false);
                switchFragment(mFragmentMall).commit();
                break;
            case R.id.llayout_me:
                setSelect(mLlayoutHome, false);
                setSelect(mLlayoutMall, false);
                setSelect(mLlayoutMe, true);

                switchFragment(mFragmentMine).commit();
                break;
            default:
                break;
        }
    }


    /**
     * 切换Fragment
     *
     * @param targetFragment 目标Fragment
     *                       * @return
     */
    private FragmentTransaction switchFragment(Fragment targetFragment) {

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!targetFragment.isAdded()) {
            //第一次使用switchFragment()时currentFragment为null，所以要判断一下
            if (mCurrentFragment != null) {
                transaction.hide(mCurrentFragment);
            }
            transaction.add(R.id.main_content, targetFragment, targetFragment.getClass().getName());
        } else {
            transaction
                    .hide(mCurrentFragment)
                    .show(targetFragment);
        }
        mCurrentFragment = targetFragment;
        return transaction;
    }


    /**
     * 设置选中状态
     *
     * @param view       选择的视图
     * @param isSelected 选择的状态
     */
    public void setSelect(View view, boolean isSelected) {
        view.setSelected(isSelected);
        view.findViewById(R.id.menu_image).setSelected(isSelected);
        view.findViewById(R.id.menu_text).setSelected(isSelected);

    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }


    }

    @Override
    protected void onDestroy() {
        EventUtil.getInstance().unregister(this);
        if (mImmersionBar != null) {
            mImmersionBar.destroy();
        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    /**
     * 检测更新
     */
    private void checkAndUpdate() {
        HashMap<String, String> params = new HashMap<>(2);
        params.put("appType", "OWNER_APP");
        params.put("numberVersion", String.valueOf(updateCode));
        new UpdateAppManager
                .Builder()
                //当前Activity
                .setActivity(this)
                .setParams(params)
                .setPost(false)
                //更新地址
                .setUpdateUrl(updateUrl)
                //实现httpManager接口的对象
                .setHttpManager(new OkGoUpdateHttpUtil())
                .build()
                .update();

    }


}


